package lesson.clazz;

import lesson.db.DbUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ClazzService {



    /**
     * 保存班级
     */
    public String saveClazz(Clazz clazz) {

        if (checkExist(clazz)) {
            return "该名称的班级已存在";
        }

        if (clazz.getId() == null) {
            SqlSession session = DbUtil.getSession(true);
            try{

                ClazzDao clazzDao = session.getMapper(ClazzDao.class);
                clazzDao.addClazz(clazz);
            }finally {

                session.close();
            }

        } else {
            SqlSession session = DbUtil.getSession(true);
            try{
                ClazzDao clazzDao = session.getMapper(ClazzDao.class);
                clazzDao.updateClazz(clazz);

            }finally {

                session.close();
            }
        }

        return null;

    }


    /**
     * 检测叫这个名字的用户是否存在
     * @param clazz
     * @return
     */
    public boolean checkExist(Clazz clazz) {
        SqlSession session = DbUtil.getSession(true);
        try{
            ClazzDao clazzDao = session.getMapper(ClazzDao.class);
            boolean exist = clazzDao.checkExist(clazz);
            return exist;

        }finally {

            session.close();
        }
    }

    /**
     * 关键字查询
     *
     * @param gradeId
     * @param keywords
     * @return
     */
    public List<Clazz> list(Integer gradeId, String keywords) {
        SqlSession session = DbUtil.getSession(true);
        try{
            ClazzDao clazzDao = session.getMapper(ClazzDao.class);
            List<Clazz> list = clazzDao.list(gradeId, keywords);
            return list;
        }finally {
            session.close();

        }


    }


    public String del(Integer id) {
        SqlSession session = DbUtil.getSession(true);
        try{
            ClazzDao clazzDao = session.getMapper(ClazzDao.class);
            clazzDao.delClazz(id);

        }finally {
            session.close();

        }

        return null;
    }

    public Clazz getById(Integer id) {
        SqlSession session = DbUtil.getSession(true);
        try{
            ClazzDao clazzDao = session.getMapper(ClazzDao.class);
            Clazz clazz = clazzDao.getById(id);
            return clazz;

        }finally {

            session.close();
        }
    }

    /**
     * 根据年级名称和班级名称获取班级id
     * @param gradeName
     * @param className
     * @return
     */
    public Integer getClassIdByNames(String gradeName, String className) {
        SqlSession session = DbUtil.getSession(true);
        try{
            ClazzDao clazzDao = session.getMapper(ClazzDao.class);
            Clazz clazz = clazzDao.getByNames(gradeName, className);
            return clazz == null ? null : clazz.getId();

        }finally {
            session.close();

        }

    }

}
